<?php

namespace App\Task;

use App\Model\Play;
use App\Model\PlayDatum;
use App\Utils\Enum\MatchEnum;

class SyncCompleteMatchInfoTask extends BaseSyncTask
{
    const int NEAR_TIME = 6 * 3600;

    public function execute(): void
    {
        parent::execute();
        $curId = 0;
        $success = 0;
        while (true) {
            $nearEndMatchTime = time() - self::NEAR_TIME;
            $matchList = Play::query()->where([['id', '>', $curId], ['match_status', '=', MatchEnum::MATCH_STATUS_END], ['match_end_time', '>', $nearEndMatchTime]])->orderBy('id')->limit(100)->select()->get();
            if ($matchList->isEmpty()) {
                break;
            }
            foreach ($matchList as $match) {
                $this->syncInit($match['match_id']);
                $curId = $match['id'];
                $detail = $this->api->getMatchInfo($match['match_id']);
                if (empty($detail)) {
                    $this->logger->warning("比赛({$match['match_id']})通过接口获取详情失败或空");
                    continue;
                }
                $update = [];
                $fields = [];
                //最佳球员
                if (!empty($detail['data']['result']['bestPlayers'])) {
                    $fields[] = '最佳球员';
                    $update['best_players'] = new_json_encode($detail['data']['result']['bestPlayers']);
                }
                //阵容
                if($this->toSync('lineup')) {
                    $lineup = $this->api->getMatchLineup($match['match_id']);
                    if ($lineup && !empty($lineup['data']['result'])) {
                        $fields[] = '阵容';
                        $update['lineup'] = new_json_encode($lineup['data']['result']);
                        $this->setSyncFlag('lineup');
                    }
                }

                //分析
                if($this->toSync('analysis')) {
                    $analysis = $this->api->getMatchAnalysis($match['match_id']);
                    if ($analysis && !empty($analysis['data']['result'])) {
                        $fields[] = '分析';
                        $update['analysis'] = new_json_encode($analysis['data']['result']);
                        $this->setSyncFlag('analysis');
                    }
                }

                //重要事件
                if ($this->toSync('incidents')) {
                    $incidents = $this->api->getMatchIncidents($match['match_id']);
                    if ($incidents && !empty($incidents['data']['result'])) {
                        $fields[] = '重要事件';
                        $update['incidents'] = new_json_encode($incidents['data']['result']);
                        $this->setSyncFlag('incidents');
                    }
                }

                //球队统计
                if ($this->toSync('team_stats')) {
                    $teamStats = $this->api->getMatchTeamStats($match['match_id']);
                    if ($teamStats && !empty($teamStats['data']['result'])) {
                        $fields[] = '球队统计';
                        $update['team_stats'] = new_json_encode($teamStats['data']['result']);
                        $this->setSyncFlag('team_stats');
                    }
                }

                //趋势
                if($this->toSync('trend')) {
                    $trend = $this->api->getMatchTrend($match['match_id']);
                    if ($trend && !empty($trend['data']['result'])) {
                        $fields[] = '趋势';
                        $update['trend'] = new_json_encode($trend['data']['result']);
                        $this->setSyncFlag('trend');
                    }
                }

                //情报
                if($this->toSync('news')) {
                    $news = $this->api->getMatchNews($match['match_id']);
                    if ($trend && !empty($news['data']['result'])) {
                        $fields[] = '情报';
                        $update['news'] = new_json_encode($trend['data']['result']);
                        $this->setSyncFlag('news');
                    }
                }

                if (!empty($update)) {
                    $ret = PlayDatum::query()->where('match_id', $match['match_id'])->update($update);
                    if ($ret) {
                        $success++;
                        $this->logger->info(sprintf('成功更新比赛 %s %s VS %s [%s]', date('Y-m-d H:i', $match['match_time']), $match['home_team_name'], $match['away_team_name'], implode(' ', $fields)));
                    }
                }
            }
        }
        $this->logger->info(sprintf('成功更新[%s]长比赛的数据', $success));
    }
}